package com.shuhe.handler;

import com.alibaba.fastjson.JSONObject;
import com.shuhe.JettyServer;
import com.shuhe.domain.mxgc.SqlRequestBody;
import com.shuhe.domain.token.Token;

import javax.servlet.http.HttpServletRequest;

import java.lang.reflect.Field;
import java.util.ArrayList;

import static com.shuhe.handler.ServiceDetail.getMyDefaultDbName;
import static com.shuhe.handler.ServiceDetail.reqOperateLog;
import static com.shuhe.handler.ServiceHandler.*;

public class CommonHandler {

    public static void reqExpire(HttpServletRequest req, JSONObject bodyJson) throws Exception {
        String tokenKey = req.getHeader("token");
        Token token = JettyServer.getGlobalToken(tokenKey);
        SqlRequestBody sqlReq = JSONObject.toJavaObject(bodyJson, SqlRequestBody.class);
        //记录操作日志
        reqOperateLog(sqlReq);
        if (!sqlReq.getOperateType().equals("reqMakeToken") && !sqlReq.getOperateType().equals("reqLogin")
                && !sqlReq.getOperateType().equals("reqVerify")
                && !sqlReq.getOperateType().equals("reqUserQuit")
                && !sqlReq.getOperateType().equals("reqTaskExecute")
                && token == null) {
            throw new Exception("无权操作");
        }
        if (token != null) {
            if (token.checkExpire(tokenKey)) {
                throw new Exception("过期操作，请重新登录");
            } else {
                token.resetExpire();
                JettyServer.setGlobalToken(tokenKey, token);
            }
        }
    }

    public static String getFirstSelfDb(String userName) throws Exception{
        SqlRequestBody sqlReq = new SqlRequestBody();
        sqlReq.setUserName(userName);
        ArrayList<Object> dbs = getMyDefaultDbName(sqlReq);
        Object db = dbs.get(0);
        String value = getDynamicObjectValue(db, 0);
        return value;
    }

    public static String getDynamicObjectValue(Object dest, int fieldPos) throws Exception {
        Field targetField = dest.getClass().getDeclaredFields()[fieldPos];
        targetField.setAccessible(true);
        return targetField.get(dest).toString();
    }
}
